package cn.est.controller;

import cn.est.dto.Result;
import cn.est.dto.UsersToken;
import cn.est.service.UsersService;
import cn.est.util.ResultUtil;
import cn.est.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class UsersController {
    @Autowired
    private UsersService usersService;

    @PostMapping("/api/user/login/sms")
    public Result LoginSms(String phone,String sms) {
        UsersToken usersToken = usersService.loginSms(phone,sms);
        return ResultUtil.success(usersToken);
    }

    @GetMapping("/api/user/info")
    public Result info(@RequestHeader("token") String token) {
        UserVO userVO = usersService.getUserInfo(token);
        return ResultUtil.success(userVO);
    }

    //重定向到QQ登录的界面
    @GetMapping("/api/user/login/qq")
    public void LoginQQ(HttpServletResponse response) throws IOException {

        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101884596&redirect_uri=http://www.0769bdqn.com/api/login&state=123456";
        response.sendRedirect(url);
    }

    @GetMapping("/api/login")
    public void login(String code,String state,HttpServletResponse response) throws IOException {
        UsersToken usersToken =usersService.loginQQ(code);
        UserVO info = usersService.getUserInfo(usersToken.getToken());
        //转换编码格式
        String encode = URLEncoder.encode(info.getUserName(), "UTF-8");
        response.sendRedirect("http://localhost:8080/redirect?token="+usersToken.getToken()+"&userInfo="+encode);
    }
}
